package com.guet.news_main.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guet.common.utils.R;
import com.guet.news_main.entity.NewsArticle;
import com.guet.news_main.service.NewsArticleService;
import com.guet.news_main.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Classname ReadCountController
 * @Description TODO
 * @Date 2022/1/6 11:51
 * @Author csp
 */
@RestController
@RequestMapping("readCount")
@CrossOrigin
public class ReadCountController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    NewsArticleService service;

    /**
     * 点赞
     * @param kind
     * @return
     */
    @GetMapping("/{kind}/{id}")
    public R readCount(@PathVariable String kind,@PathVariable String id){
        double incr;
        if(kind.equals("zhan")){
             incr = redisUtil.hincr("zhan", id, 1);
        }
        else if(kind.equals("fensi")){
             incr = redisUtil.hincr("fensi", id, 1);

        }
        else{
            incr = redisUtil.hincr("guanzhu", id, 1);
        }
        return R.ok().data("readCount",incr);
    }

    @GetMapping("/getInfo/{id}")
    public R getInfo(@PathVariable String id){
        Object zhan = redisUtil.hget("zhan", id);
        Object fensi = redisUtil.hget("fensi", id);
        Object guanzhu = redisUtil.hget("guanzhu", id);
        Integer defaultNum=0;
      /*  return R.ok().data("zhan",zhan).data("guanzhu",guanzhu).data("fensi",fensi);*/
        return R.ok().data("zhan",zhan==null?defaultNum:zhan).data("guanzhu",guanzhu==null?defaultNum:guanzhu).data("fensi",fensi==null?defaultNum:fensi);
    }

    /**
     * 访问量统计
     * @param id 新闻id
     * @return
     */
    @PostMapping("/count/{id}")
    public R articleReadCount(@PathVariable long id){
        NewsArticle byId = service.getById(id);
        Integer sort = byId.getSort();
        sort++;
        byId.setSort(sort);
        QueryWrapper<NewsArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("id",byId.getId());
        boolean update = service.update(byId, wrapper);
        return update?R.ok():R.error();
    }

    @GetMapping("/getHot")
    public R getHot(){
        QueryWrapper<NewsArticle> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sort");
        Page<NewsArticle> page = new Page<>(1, 10);
        IPage<NewsArticle> page1 = service.page(page, wrapper);
        List<NewsArticle> records = page1.getRecords();
        return R.ok().data("rows",records);
    }
}